/*
 * uart0_dbg.c
 *
 * Description:
 * 		This is a preliminary debug driver to out characters on UART0 line.
 * 		This driver not be used after proper kernel drivers are initialized.
 *
 * 		Provides funtion to print a character on screen and an init routine
 * 		to register the put character function for use with printk()
 *
 *  Created on: Nov 30, 2013
 *      Author: Nishanth
 */

#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <mmu.h>
#include <mmio.h>
#include "uart0_dbg.h"

int printk(char *fmt, ...);


extern void registerPutcFunc(void *pFunc);

/**************************************************************************
 * Description:
 * 		Prints one character through UART0. Routine also takes care or
 * 		line-feed - carriage return combination
 *
 * 	Input:
 * 		Single character to be printed
 *
 * 	Output:
 * 		None
 *************************************************************************/
static void uart0_dbg_putch(const char c)
{
//	volatile uint8_t *thr_reg = (uint8_t *)UART0_DBG_THR;
//	volatile uint8_t *lsr_reg = (uint8_t *)UART0_DBG_LSR;

	// Write the byte to THR register
//	*thr_reg = (uint8_t)c;
	writeMmioReg8((uint8_t *)UART0_DBG_THR, c);
	// Wait till THR is empty by checking TX FIFO Empty bit in LSR register
//	while ( !(*lsr_reg && UART0_DBG_LSR_TXFIFOE));
	while ( !(readMmioReg8((uint8_t *)UART0_DBG_LSR) & UART0_DBG_LSR_TXFIFOE));

	// If Line-feed character, then
	// we need to write a carriage return as well
	if (c == '\n')
		uart0_dbg_putch('\r');

	return;
}

/**************************************************************************
 * Description:
 * 		Register uart0_dbg_putch() for printing characters
 *
 * 	Input:
 * 		None
 *
 * 	Output:
 * 		INT status, SUCCESS or FAILURE.
 **************************************************************************/
int uart0_dbg_init()
{
	UART0_DBG_BASE = mapMmioPages(VIRT_ADDR_NONE, (PhyAddr)UART0_MMIO_BASE_PHY, 1);

	registerPutcFunc(&uart0_dbg_putch);

	return 0;
}

